/**
 * 北京中流科技有限公司 版权所有
 * http://www.chinasoa.com.cn
 */
package cn.com.chinasoa.course.subscribe;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

import cn.com.chinasoa.course.subscribe.util.DataTypeUtil;
import cn.com.chinasoa.course.subscribe.util.SubscribeDocumentHelper;

import com.x4ee.soa.portal.framework.core.ActionConfig;
import com.x4ee.soa.portal.framework.core.ActionFilter;
import com.x4ee.soa.portal.framework.core.BaseRequestFilter;
import com.x4ee.soa.portal.framework.core.FrameworkConfig;

/**
 * @author 刘洋(liuyang@chinasoa.com.cn)
 * 2007-11-4下午05:26:50
 */
public class SubscribeOrderDownActionFilter extends BaseRequestFilter
	implements ActionFilter {
	
	private static String SUCCESS = "success";
	private static String FAILED = "error";
	
	public String process(ActionRequest actionRequest, ActionResponse actionResponse,
			ActionConfig actionConfig) throws PortletException, IOException {
		
		String orderFileName = actionRequest.getParameter("orderFileName");
		String orderId = actionRequest.getParameter("orderId");
		
		boolean success = false;
		if((orderFileName!=null)&&(orderId!=null)){
			long orderIdLong = DataTypeUtil.parseLong(orderId);
			if(orderIdLong>=0){
				HttpServletResponse portalResponse = FrameworkConfig.getPortalResponse(actionResponse);
				if(portalResponse!=null){
					portalResponse.setHeader("Cache-Control", "max-age=0; must-revalidate");
					portalResponse.setHeader("Content-Type","application/octet-stream;charset=gb2312");
					portalResponse.setHeader("Cache-Control", "max-age=0; must-revalidate");
					portalResponse.addHeader("Content-Disposition", "attachment; filename=" +orderFileName);
					
					File tempFile = File.createTempFile(orderFileName,"");
					FileOutputStream tempFileOutputStream = new FileOutputStream(tempFile);
					SubscribeDocumentHelper.writeDocument(orderIdLong,tempFileOutputStream);
					tempFileOutputStream.close();
					
					FileInputStream tempFileInputStream = new FileInputStream(tempFile);
					IOUtils.copy(tempFileInputStream,portalResponse.getOutputStream());
					tempFileInputStream.close();
					
					portalResponse.flushBuffer();
					
					success=true;
				}
			}
		}
		if(success)return SUCCESS;
		else return FAILED;
	}

}
